//
//  HMOauthViewController.swift
//  HMWeibo1
//
//  Created by liGordon on 16/4/9.
//  Copyright © 2016年 lifuli. All rights reserved.
//

import UIKit

import SVProgressHUD

class HMOauthViewController: UIViewController {
    
    
    /// 在loadView里面赋值  不用设置view的大小
    override func loadView() {

        // 赋值
        view = webView
        
        
        // 设置webView代理
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
      
        // 设置背景颜色 不然在modal出来时会透明看到后面的控制器
        view.backgroundColor = GlobalBGColor
        
        
        // 设置导航栏
        
        setupNavigationBar()
        HMPrint("oauthURL: \(oauthURL())")
        
        // 加载授权界面
        let url = oauthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
        
        // 进度转 一直存在不消失  除非dismiss
        SVProgressHUD.showWithStatus("正在加载登录界面....")
        
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
    }
    
    /// 拼接Oauth授权登录界面的url( GET )
    private func oauthURL() -> NSURL {
        let urlString = OauthUrl + "?client_id=" + client_id +  "&redirect_uri=" + redirect_uri
        return NSURL(string: urlString)!
    }
    
    
    /// 设置导航栏左右
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("autoFill"))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("close"))
    }
    
    
    /// Mark: - 按钮点击事件
    @objc private func autoFill() {
        // 使用webView执行js代码
        let js = "document.getElementById('userId').value = '18581478435';document.getElementById('passwd').value = '19931203lfl'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    @objc private func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// Mark : - 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
}


// Mark: - 
extension HMOauthViewController: UIWebViewDelegate {
    // webView是否要去加载一个请求
    // true: 放行 可以加载
    // false: 拦住 不去加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        HMPrint("webView是否要去加载一个请求: \(urlString)")
        
        // 当如果是  http://www.baidu.com/ 开头的地址,我们自己来处理拦截不让他去加载,其他的地址放行
        // 点击取消按钮: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        
        // 点击授权: http://www.baidu.com/?code=4e496956aa012e11299494637e9ca536
        
        // 判断是否是授权回调地址
        let isRedirectURL = urlString!.hasPrefix(redirect_uri)
        
        if !isRedirectURL {
            // 不是授权回调地址,让他加载
            return true
        } else {
            // 授权回调地址, 点击的是取消或授权
            // 判断点击的是取消还是授权按钮, 如果?后面是code=开头就是授权按钮
            // query是get请求?后面的东西
            let query = request.URL?.query
            HMPrint("query: \(query)")
            
            let codeString = "code="
            
            // 判断query是否是code=开头
            if query!.hasPrefix(codeString) {
                // query是code=开头,授权按钮
                HMPrint("授权按钮点击了:\(query)")
                // 截取 code=4e496956aa012e11299494637e9ca536 里面code=后面的内容
                //                let index = codeString.endIndex
                //                let code = query!.substringFromIndex(index)
                
                // 截取字符串转成NSString
                let code = (query! as NSString).substringFromIndex(codeString.characters.count)
                HMPrint("code: \(code)")
                
                
                // 获取access_token, 当使用post获取accessToken成功后下次输入密码不会弹出授权按钮,会直接去获取accessToken,如果想看到授权按钮需要去取消授权
//                loadAccessToken(code)
                
                
                /// 3. 调用loadAccessToken 准备闭包并传递
                HMUserAccountViewModel.sharedInstance.loadAccessToken(code, loadAccessTokenCallback: { (error) -> () in
                    if error != nil {
                        HMPrint("加载accessToken 出错: \(error)")
                        SVProgressHUD.showErrorWithStatus("网络不给力")
                        
                        // 延时关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                        return
                    }
                    
                    // 成功了
                    HMPrint("加载accessToken 成功了")
                    self.close()
                    
                    // 跳转到欢迎界面
                    let controller = HMWelcomeViewController()
                    
                    (UIApplication.sharedApplication().delegate as! AppDelegate).switchViewController(controller)
                })
                
            }else {
                // 取消按钮
                HMPrint("取消按钮点击了")
                
                // 关闭控制器
                close()
            }
            return false
        }
        
    }
    
//    /// 获取accessToken
//    private func loadAccessToken(code: String) {
//        // 1. URLString
//        let urlString = accessTokenURLString
//        
//        // 2. 参数.字典
//        let parameters = [
//        "client_id": client_id,
//        "client_secret": client_secret,
//        "grant_type": grant_type,
//        "code": code,
//        "redirect_uri": redirect_uri
//        ]
//        
//        /// 发送请求 afn.POST
//   HMNetwork.shareInstance.POST(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
//    
//    // as: 表示类型转换
//    // as?: 有可能转成功,有可能转失败
//    // as!: 一定能转成功,如果转换失败,直接挂了
//    
//    let result = responseObject as? [String: AnyObject]
//    
//    if let dict = result {
//        // 字典转模型
//        let userAccount = HMUserAccount(dict: dict)
//        
//        HMPrint("字典转模型成功: \(userAccount)")
//    }
//    
//    }) { (task, error) -> Void in
//        HMPrint("accessToken 请求失败: \(error)")
//        }
//    }
    
    /// webView加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    /// webView加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        // 当设置showErrorWithStatus 会将其他的HUD dismiss
        HMPrint("error: \(error)")
        if error?.code == 102 {
            // 点击取消,加载被中断
            return
        }
        
        SVProgressHUD.showErrorWithStatus("网络不给力..")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
        
    }
    
}